<?php
namespace App\Repositories;

use App\Traits\SingletonTrait;
use Hyperf\DbConnection\Db;

class AdminRepository extends AbstractRepository
{
    use SingletonTrait;
    public function model()
    {
        return 'App\\Model\\Admin';
    }

    public function store($data)
    {
        $model = isset($data['id'])&&$data['id']?$this->getById($data['id']):new $this->model();
        if($data['password']){
            $data['password'] = password_hash($data['password'],PASSWORD_BCRYPT);
        }
        $unit=null;
        if(isset($data['unit_id'])&&$data['unit_id']){
            $unit = CompanyUnitRepository::getInstance()->getById($data['unit_id']);
        }
        $model->fill($data);
        $model->parent_id =  $unit?object_get($unit,'parent_id',0):0;
        $model->role_id = $data['role_id'];
        DB::beginTransaction();
        try{
            if(!$model->save()){
                throw new \Exception('数据保存失败');
            }
            DB::commit();
        }catch (\Throwable $exception){
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
        return $this->success($model);
    }
}